package com.my.controller;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.my.pojo.Address;
import com.my.pojo.User;
import com.my.service.IAddressService;
import com.my.util.JWTUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@CrossOrigin("*")
@RequestMapping("/address")
public class AddressController {
    IAddressService addressService;

    @Autowired
    public void setAddressService(IAddressService addressService) {
        this.addressService = addressService;
    }

    RedisTemplate<String, String> redisTemplate;

    @Autowired
    public void setRedisTemplate(RedisTemplate<String, String> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    private String listAddressToJSON(List<Address> addressList) {
        JsonArray jsonArray = new JsonArray();
        addressList.forEach(e -> {
            if (e.getStatus() != -1) {
                JsonObject jsonObject = new JsonObject();
                jsonObject.addProperty("addressId", e.getAddress_id());
                jsonObject.addProperty("province", e.getProvince());
                jsonObject.addProperty("city", e.getCity());
                jsonObject.addProperty("district", e.getDistrict());
                jsonObject.addProperty("address", e.getAddress());
                jsonObject.addProperty("code", e.getCode());
                jsonObject.addProperty("phone", e.getPhone());
                jsonObject.addProperty("name", e.getName());
                jsonObject.addProperty("status", e.getStatus());
                jsonArray.add(jsonObject);
            }
        });
        return jsonArray.toString();
    }

    private void putMessage(Map<String, String> map, String code, String message) {
        map.put("code", code);
        map.put("message", message);
    }

    @RequestMapping("/show")
    public String showAddress(HttpServletRequest req) {
        Map<String, String> map = new HashMap<>();

        Integer userId = JWTUtils.getId(req.getHeader("token"));
        if (userId == null) {
            putMessage(map, "500", "无效token");
        } else {
            List<Address> addressList = addressService.showAddress(userId);
            putMessage(map, "200", "Success");
            map.put("address", listAddressToJSON(addressList));
        }

        return new Gson().toJson(map);
    }

    @RequestMapping("/add")
    public String addAddress(String province, String city, String district, String address, String code, String phone, String name, HttpServletRequest req) {
        Map<String, String> map = new HashMap<>();
        if (province.trim().equals("") || city.trim().equals("") || district.trim().equals("") || address.trim().equals("")) {
            putMessage(map, "500", "数据非法");
        } else {
            Integer userId = JWTUtils.getId(req.getHeader("token"));
            if (userId == null) {
                putMessage(map, "501", "token解析失败");
            } else {
                Address a = new Address();
                a.setProvince(province);
                a.setCity(city);
                a.setDistrict(district);
                a.setAddress(address);
                a.setCode(code);
                a.setPhone(phone);
                a.setName(name);
                User user = new User();
                user.setUserId(userId);
                a.setUser(user);
                a.setStatus(0);
                Integer res = addressService.addAddress(a);
                if (res == -1) {
                    putMessage(map, "502", "sql错误");
                } else if (res == 0) {
                    putMessage(map, "200", "Success");
                } else {
                    putMessage(map, "555", "未知错误");
                }
            }
        }
        return new Gson().toJson(map);
    }

    @RequestMapping("/update")
    public String updateAddress(Integer id, String province, String city, String district, String address, String code, String phone, String name) {
        Map<String, String> map = new HashMap<>();
        if (province.trim().equals("") || city.trim().equals("") || district.trim().equals("") || address.trim().equals("")) {
            putMessage(map, "500", "数据非法");
        } else {
            Address a = this.addressService.selById(id);
            a.setProvince(province);
            a.setCity(city);
            a.setDistrict(district);
            a.setAddress(address);
            a.setCode(code);
            a.setPhone(phone);
            a.setName(name);
            Integer res = addressService.addAddress(a);
            if (res == -1) {
                putMessage(map, "502", "sql错误");
            } else if (res == 0) {
                putMessage(map, "200", "Success");
            } else {
                putMessage(map, "555", "未知错误");
            }
        }
        return new Gson().toJson(map);
    }

    @RequestMapping("/delete")
    public String deleteAddress(Integer addressId, HttpServletRequest req) {
        Map<String, String> map = new HashMap<>();

        if (addressId <= 0) {
            putMessage(map, "500", "非法参数");
        } else {
            Integer userId = JWTUtils.getId(req.getHeader("token"));
            if (userId == null) {
                putMessage(map, "501", "token解析失败");
            } else {
                Integer res = addressService.deleteAddress(addressId, userId);
                if (res == 0) {
                    putMessage(map, "200", "Success");
                } else if (res == -1) {
                    putMessage(map, "502", "非法操作");
                } else if (res == -2) {
                    putMessage(map, "503", "sql错误");
                } else {
                    putMessage(map, "555", "未知错误");
                }
            }
        }
        return new Gson().toJson(map);
    }

    @RequestMapping("/selById")
    public String selById(Integer id) {
        Map<String, String> map = new HashMap<>();

        Address address = this.addressService.selById(id);
        if (address != null) {
            this.putMessage(map, "200", "success");
            JsonObject jsonObject = new JsonObject();
            jsonObject.addProperty("addressId", address.getAddress_id());
            jsonObject.addProperty("province", address.getProvince());
            jsonObject.addProperty("city", address.getCity());
            jsonObject.addProperty("district", address.getDistrict());
            jsonObject.addProperty("address", address.getAddress());
            jsonObject.addProperty("code", address.getCode());
            jsonObject.addProperty("phone", address.getPhone());
            jsonObject.addProperty("name", address.getName());
            jsonObject.addProperty("status", address.getStatus());
            map.put("address", jsonObject.toString());
        } else {
            this.putMessage(map, "500", "false");
        }
        return new Gson().toJson(map);
    }

    @RequestMapping("/updateStatus")
    public String updateStatus(Integer ori_id, Integer id) {
        Map<String, String> map = new HashMap<>();
        Address address1 = this.addressService.selById(ori_id);
        if (address1 != null) {
            address1.setStatus(0);
            this.addressService.addAddress(address1);
            Address address2 = this.addressService.selById(id);
            if (address2 != null) {
                address2.setStatus(1);
                this.addressService.addAddress(address2);
                this.putMessage(map, "200", "success");
            } else {
                address1.setStatus(1);
                this.addressService.addAddress(address1);
                this.putMessage(map, "500", "error");
            }
        } else {
            this.putMessage(map, "500", "error");
        }
        return new Gson().toJson(map);
    }
}
